<?php

namespace app\store\controller;

use app\store\model\Order as OrderModel;
use app\store\model\Express as ExpressModel;
use app\store\model\store\shop\Clerk as ShopClerkModel;
use app\store\model\store\Shop as ShopModel;
use app\store\model\User as UserModel;
use app\common\service\order\Refund as RefundService;
use app\api\model\Setting as SettingModel;
use think\db;
use app\store\model\Wxapi;
/**
 * 订单管理
 * Class Order
 * @package app\store\controller
 */
class Order extends Controller
{
    /**
     * 待发货订单列表
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function delivery_list()
    {
        return $this->getList('待发货订单列表', 'delivery');
    }

    /**
     * 待收货订单列表
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function receipt_list()
    {
        return $this->getList('待收货订单列表', 'receipt');
    }

    /**
     * 待付款订单列表
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function pay_list()
    {
        return $this->getList('待付款订单列表', 'pay');
    }

    /**
     * 已完成订单列表
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function complete_list()
    {
        return $this->getList('已完成订单列表', 'complete');
    }

    /**
     * 已取消订单列表
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function cancel_list()
    {
        return $this->getList('已取消订单列表', 'cancel');
    }

    /**
     * 全部订单列表
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function all_list()
    {
        return $this->getList('全部订单列表', 'all');
    }

    /**
     * 订单详情
     * @param $order_id
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function detail($order_id)
    {
    
        // 订单详情
        $detail = OrderModel::detail($order_id);
        //用户等级
        $user_grade_data = Db::table('yoshop_user_grade')->where('status', '=', '1')
            ->where('is_delete', '=', '0')->column('grade_id,name');
        // 物流公司列表
        $expressList = ExpressModel::getAll();
        // 门店店员列表
        $shopClerkList = (new ShopClerkModel)->getList(true);
        $proData = Db::table('yoshop_region')->where('pid',0)->select();
        return $this->fetch('detail', compact(
            'detail',
            'expressList',
            'shopClerkList',
            'proData',
            'user_grade_data'
        ));
    }

    /**
     * 确认发货
     * @param $order_id
     * @return array
     * @throws \app\common\exception\BaseException
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function delivery($order_id)
    {
    	$model = OrderModel::detail($order_id);
    	// return $model->delivery($this->postData('order'));
        if ($model->delivery($this->postData('order'))) {
            return $this->renderSuccess('发货成功');
        }
        return $this->renderError($model->getError() ?: '发货失败');
    }

    /**
     * 修改订单价格
     * @param $order_id
     * @return array
     * @throws \think\exception\DbException
     */
    public function updatePrice($order_id)
    {
        $model = OrderModel::detail($order_id);
        if ($model->updatePrice($this->postData('order'))) {
            return $this->renderSuccess('修改成功');
        }
        return $this->renderError($model->getError() ?: '修改失败');
    }

    /**
     * 订单列表
     * @param string $title
     * @param string $dataType
     * @return mixed
     * @throws \think\exception\DbException
     */
    private function getList($title, $dataType)
    {
        // 订单列表
        $model = new OrderModel;
        $list = $model->getList($dataType, $this->request->param());
        //用户等级
        $user_grade_data = Db::table('yoshop_user_grade')->where('status', '=', '1')
            ->where('is_delete', '=', '0')->column('grade_id,name');
        // 自提门店列表
        $shopList = ShopModel::getAllList();
        return $this->fetch('index', compact('title', 'dataType', 'list', 'shopList','user_grade_data'));
    }

    /**
     * 修改备注
     * @param $order_id
     * @return array
     * @throws \think\exception\DbException
     */
    public function updateRemark($order_id)
    {
        $model = OrderModel::detail($order_id);
        if ($model->updateRemark($this->postData('order'))) {
            return $this->renderSuccess('修改成功');
        }
        return $this->renderError($model->getError() ?: '修改失败');
    }
    public function public_getProvince(){
        $data = Db::table('yoshop_region')->where('pid',0)->select();
        return $this->renderSuccess('获取身份','',$data);
    }
    public function public_getCity(){
        $provinceid = input('get.provinceid');
        $data = Db::table('yoshop_region')->where('pid',$provinceid)->select();
        return $this->renderSuccess('获取身份','',$data);
    }
    public function public_getArea(){
        $cityid = input('get.cityid');
        $data = Db::table('yoshop_region')->where('pid',$cityid)->select();
        return $this->renderSuccess('获取身份','',$data);
    }
    public function updateAddress(){
        $data = input('post.');
        $status = Db::table('yoshop_order_address')->where('order_id',$data['order_id'])->update(
            [
                'name'=>$data['address_name'],
                'phone'=>$data['address_phone'],
                'province_id'=>$data['address_province'],
                'city_id'=>$data['address_city'],
                'region_id'=>$data['address_region'],
                'detail'=>$data['address_detail'],
            ]
        );
        //array(2) { ["order"]=> array(4) { ["address_province"]=> string(3) "351" ["address_city"]=> string(3) "352" ["address_region"]=> string(3) "353" ["address_detail"]=> string(13) "人民路3号" } ["order_id"]=> string(5) "12029" }
        if($status){
            return $this->renderSuccess('修改成功');
        }
        return $this->renderError('修改失败');
    }

    /**
     * 修改订单状态
     */
    public function updateOrder_status(){
        $data = input('post.');
        $order_model = OrderModel::detail($data['order_id']);
        if($data['order_status_o'] == 1){
            //取消订单（未付款订单直接取消，已付款待发货的订单，取消并退款）
            if(($order_model['order_status']['value'] == 10) || ($order_model['order_status']['value'] == 21)){
                if ($order_model['delivery_status']['value'] == 10) {
                    if($order_model['pay_status']['value'] == 20){
                        //已支付，退款并取消
                        if ($order_model->orderCancelPlat($order_model)) {
                            return $this->renderSuccess('订单取消成功');
                        }
                        return $this->renderError('订单取消失败');
                    }else{
                        //未付款，直接取消
                        $status = Db::table('yoshop_order')->where('order_id',$order_model['order_id'])->update(
                            [
                                'order_status'=>20,
                            ]
                        );
                        if($status){
                            return $this->renderSuccess('订单取消成功');
                        }
                        return $this->renderError('订单取消失败');
                    }
                }else{
                    return $this->renderError('已发货订单不可取消');
                }
            }
        }elseif ($data['order_status_o'] == 2){
            //完成订单（已付款的订单，修改为已完成。可售后）
            if(($order_model['order_status']['value'] == 10) && ($order_model['pay_status']['value'] == 20)){
                $status = Db::table('yoshop_order')->where('order_id',$order_model['order_id'])->update(
                    [
                        'order_status'=>30,
                        'delivery_status'=>20,
                        'delivery_time'=>time(),
                        'receipt_status'=>20,
                        'receipt_time'=>time(),
                    ]
                );
            }
            if($status){
                return $this->renderSuccess('订单操作成功');
            }
            return $this->renderError('订单操作失败');
        }elseif ($data['order_status_o'] == 3){
            //终结订单（已付款或已完成订单，修改为已完成，并设置超过售后期限。不可售后）
            if(($order_model['order_status']['value'] != 20) && ($order_model['pay_status']['value'] == 20)){
                $refundDays = SettingModel::getItem('trade')['order']['refund_days'];
                $receipt_time = time() - ($refundDays + 2) * 86400;
                $status = Db::table('yoshop_order')->where('order_id',$order_model['order_id'])->update(
                    [
                        'order_status'=>30,
                        'delivery_status'=>20,
                        'delivery_time'=>time(),
                        'receipt_status'=>20,
                        'receipt_time'=>$receipt_time,
                        'is_settled'=>1,
                        'is_comment'=>1
                    ]
                );
            }
            if($status){
                return $this->renderSuccess('订单操作成功');
            }
            return $this->renderError('订单操作失败');
        }else{
            return $this->renderError('参数错误');
        }
    }
    /**
     * 退款审核
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function refund_audit()
    {
        return $this->getList('退款审核', 'refund');
    }

    /**
     * @return array|bool
     * @throws \think\exception\DbException
     * 平台退款
     */
    public function receipt_plat(){
        if (!$this->request->isAjax()) {
            return false;
        }
        $data = input('post.');
        if(!$data['refund_money'] || $data['refund_money'] <= 0){
            return $this->renderError('退款金额不正确');
        }
        $order_model = OrderModel::detail($data['order_id']);
        if ($order_model->receiptPlat($data)) {
            return $this->renderSuccess('操作成功');
        }
        return $this->renderError($order_model->getError() ?: '操作失败');
    }

    /**
     * @return array|bool
     * @throws \think\exception\DbException
     * 平台退款
     */
    public function sharing_receipt_plat(){
        if (!$this->request->isAjax()) {
            return false;
        }
        $data = input('post.');
        if(!$data['refund_money'] || $data['refund_money'] <= 0){
            return $this->renderError('退款金额不正确');
        }
        $order_model = \app\common\model\sharing\Order::detail($data['order_id']);
        if ($order_model->receiptPlat($data)) {
            return $this->renderSuccess('操作成功');
        }
        return $this->renderError($order_model->getError() ?: '操作失败');
    }
}
